"""
@File    :   sqlalchemy_exception.py
@Time    :   2024/04/07 15:52:51
@Author  :   Qrj
@Email   :   923207736@qq.com
@description   :   sqlalchemy相关异常的异常处理
"""


from fastapi import Request
from sqlalchemy.exc import IntegrityError

from src.enums.http_response_code import HttpResponseEnum
from src.typings import RequestValidationErrorConvertedDataT
from src.utils.sqlalchemy_model_info import SqlalchemyIntegrityErrorUtil
from src.utils.unified_response import FailApiJSONResponse


async def sqlalchemy_integrity_error_exception_handler(
    request: Request, exc: IntegrityError
):
    """处理sqlalchemy完整性错误(外键、unique、联合unique重复)异常
    最后的异常信息和RequestValidationError的异常处理信息相同
    """
    # 对错误信息进行转换, 最后将其写入data
    err_data: RequestValidationErrorConvertedDataT = (
        SqlalchemyIntegrityErrorUtil.error_data_convert(exc)
    )
    return FailApiJSONResponse(
        status_code=HttpResponseEnum.SUCCESS.value.code,
        code=HttpResponseEnum.PARAMS_VALID_ERROR.value.code,
        message=HttpResponseEnum.PARAMS_VALID_ERROR.value.msg,
        data=err_data,
    )
